from rest_framework.viewsets import ModelViewSet
from aaa import models
from rest_framework import serializers
from rest_framework.response import Response
import json
from django.http import JsonResponse
from aaa.utils.pager import myPageNumberPagination

class carefullySerializer(serializers.ModelSerializer):
    goods_name = serializers.SerializerMethodField()
    class Meta:
        model = models.CarefullyChosen
        fields = ['id','name','image','goods','goods_name']
    def get_goods_name(self,row):
        print('get_goods_name row',row.goods.all())
        ret = [ item.goods_name for item in row.goods.all()]
        print(ret)
        if len(ret) > 1:
            ret = ', '.join(ret)
            return ret
        # print('user ret',ret)
        if not ret:
            return None
        return ret[0]

class carefullyView(ModelViewSet):
    queryset = models.CarefullyChosen.objects.all()
    serializer_class = carefullySerializer
    # pagination_class = PageNumberPagination
    authentication_classes = []

    def list(self, request, *args, **kwargs):
        print('args',request._request.GET.get('pagenum'))
        # goods = models.Categories.objects.all()
        pg = myPageNumberPagination()
        xx = pg.paginate_queryset(queryset=self.queryset,request=request,view=self)
        ser = carefullySerializer(instance=xx,many=True)
        ret = {}
        ret['data'] = json.dumps(ser.data)
        print('ser',len(ret['data']),ret['data'])
        ret['total'] = self.queryset.count()
        return JsonResponse(ret)